package com.youlu.campus.web.common.base;


import com.youlu.campus.entity.UserPO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

@Slf4j
public class RequestContext {

    private static ThreadLocal<UserPO> curUser = new InheritableThreadLocal<>();

    private static ThreadLocal<Integer> curVersion = new ThreadLocal<>();

    private static ThreadLocal<String> curPlatform = new ThreadLocal<>();
    private static ThreadLocal<String> curAppId = new ThreadLocal<>();
    private static ThreadLocal<String> curAuthorizeMode = new ThreadLocal<>();

    public static void setCurAppId(String appId) {
        curAppId.set(appId);
    }

    public static String getAppId() {
        return curAppId.get();
    }

    public static void setVersion(Integer version) {
        curVersion.set(version);
    }

    public static Integer getVersion() {
        return curVersion.get();
    }

    public static UserPO getCurUser() {
        return curUser.get();
    }

    public static String getCurPlatform() {
        return curPlatform.get();
    }

    public static void setCurPlatform(String platform) {
        curPlatform.set(platform);
    }

    public static String getCurUserId() {
        return curUser.get().getId();
    }

    public static void setCurAuthorizeMode(String authorizeMode){
        curAuthorizeMode.set(authorizeMode);
    }
    public static String getCurAuthorizeMode(){
        return curAuthorizeMode.get();
    }

    public static Set<String> getCurUserIdList() {
        Set<String> list = curUser.get().getAccountInfoIdList();
        if(CollectionUtils.isEmpty(list)){
            list = new HashSet<>();
        }
        list.add(curUser.get().getId());
        return list;
    }

    public static Boolean isMobileLogin() {
        UserPO userPO = getCurUser();
        if(userPO == null || StringUtils.isBlank(userPO.getOpenId())){
            return false;
        }
        return userPO.getOpenId().contains("h5-");
    }

    public static String getUserId() {
        try {
            UserPO userPO = getCurUser();
            if (Objects.nonNull(userPO)) {
                return userPO.getId();
            }
            log.info(":>>> 当前用户未登陆:返回空");
            return "";
        } catch (Exception e) {
            log.error(":>>> 获取用户ID错误:{}", e);
            return "";
        }
    }

    public static void setCurUser(UserPO userEntity) {
        curUser.set(userEntity);
    }

    public static void clear() {
        curUser.remove();
        curVersion.remove();
        curPlatform.remove();
        curAppId.remove();
        curAuthorizeMode.remove();
    }

}
